package lion.workflow;

import java.util.ArrayList;
import java.util.List;

import lion.dev.lang.MapJ;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

/**
 *
 * 工作流状态定义
 *
 * 在同一个工作流中状态名称必须不一样
 *
 * @author lion
 * @email hl_0074@sina.com
 * @date 2014年7月22日
 */
public class WorkFlowState {

	public enum Type {
		START, END, NORMAL
	}

	private String name;
	public List<WorkFlowTransition> transitions = new ArrayList<>();
	private Type type;
	private String users;
	private String roles;
	private boolean wait;
	private String join;

	public WorkFlowState(MapJ attributes, List<WorkFlowTransition> transitions) {

		this(attributes);

		this.transitions = transitions;
	}

	public WorkFlowState(MapJ attributes) {

		this.name = attributes.getString("name");
		this.users = attributes.getString("users");
		this.roles = attributes.getString("roles");
		this.wait = attributes.getBoolean("wait");
		this.join = attributes.getString("join");

		if (attributes.getBoolean("start")) {
			this.type = Type.START;
		} else if (attributes.getBoolean("end")) {
			this.type = Type.END;
		} else {
			this.type = Type.NORMAL;
		}

	}

	public void addTransition(WorkFlowTransition transition) {


		this.transitions.add(transition);
	}

	public List<WorkFlowTransition> getTransitions() {

		return this.transitions;
	}

	public WorkFlowTransition getTransition(String transitionName) {

		for (WorkFlowTransition wft : this.transitions) {
			if (StringUtils.equals(wft.getName(), transitionName)) { return wft; }
		}

		return null;
	}

	public void executeActions(WorkflowContext context) {

	}

	public boolean hasPriv(int userId, int[] userRole) {

		// no user or role specified means everyone
		if (StringUtils.isBlank(this.users) && StringUtils.isBlank(this.roles)) { return true; }

		boolean hasPriv = false;
		if (StringUtils.isNotBlank(this.users)) {
			if (ArrayUtils.contains(this.users.split(","), String.valueOf(userId))) {
				hasPriv = true;
			}
		}
		if (!hasPriv && StringUtils.isNotBlank(this.roles)) {
			String[] roles = this.roles.split(",");
			if (userRole.length > 0) {
				for (int r : userRole) {
					if (ArrayUtils.contains(roles, r + "")) {
						hasPriv = true;
						break;
					}
				}
			}
		}
		return hasPriv;
	}

	public String getUsers() {

		return this.users;
	}

	public String getRoles() {

		return this.roles;
	}

	public String getName() {

		return this.name;
	}

	public boolean isStart() {

		return this.type == Type.START;
	}

	public boolean isEnd() {

		return this.type == Type.END;
	}

	public Type getType() {

		return this.type;
	}

	public boolean isWait() {

		return this.wait;
	}

	public String getJoin() {

		return this.join;
	}
}
